import React from "react"
import {Redirect, Route,withRouter,Switch} from "react-router-dom"
@withRouter
class Compile extends React.Component{
    constructor(){
        super()
        this.state={
            c:null
        }
    }
    static getDerivedStateFromProps(nextProps,nextState){
        let c=[]
        let {routes,isChildRoute}=nextProps //获取路由配置选项
        let {pathname}=nextProps.location //获取当前地址栏的地址
        // let target=routes.find((item)=>{return item.path===pathname})   根据地址栏地址在路由配置中寻找，判断是否为合法路由
        let isLogin=localStorage.getItem("Login-token")     //通过获取token，来判断是否已经登陆
        if(!isLogin){    //没有登陆过的，都跳转到登陆页面
            c=routes.filter((item)=>{return item.auth !== false})   //首先剔除掉路由配置中不需要验证的选项
            c=c.map((item)=>{return <Route key={item.path} path={item.path} component={item.component} exact={item.exact}></Route>})
            c.push(<Redirect key="redirect1" to="/Login"></Redirect>)
        }else{      //已经登陆
           c=routes.map((item)=>{
               return <Route key={item.path} path={item.path} exact={item.exact} component={()=>{
                        return <item.component routes={item.children} />}}></Route>})
           if(!isChildRoute){
                c.push(<Redirect key="redirect2" to="/404"></Redirect>)
           }
        }
        return {c}
    }
    render(){
        return <Switch>{this.state.c}</Switch>
    }
}
export default Compile
